package com.style.dynamic;

import com.style.core.Event;
import com.style.core.IMouse;
import com.style.core.MouseEventType;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

public class MouseDynamicProxy implements InvocationHandler {
    private Map<String, MouseEventType> map = new HashMap<>();
    private IMouse target;

    public MouseDynamicProxy() {
        map.put("click", MouseEventType.ON_CLICK);
        map.put("doubleClick", MouseEventType.ON_DOUBLE_CLICK);
        map.put("up", MouseEventType.ON_UP);
        map.put("down", MouseEventType.ON_DOWN);
        map.put("wheel", MouseEventType.ON_WHEEL);
        map.put("move", MouseEventType.ON_MOVE);
        map.put("over", MouseEventType.ON_OVER);
    }

    public Object getInstance(IMouse target) {
        this.target = target;
        Class<?> clazz = target.getClass();
        return Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        method.invoke(target, args);
        trigger(map.get(method.getName()));
        return null;
    }

    //Map相当于是一个注册器
    protected Map<Enum, Event> events = new HashMap<Enum, Event>();

    public void addLisenter(Enum eventType, Object target, Method callback) {
        //注册事件
        //用反射调用这个方法
        events.put(eventType, new Event(target, callback));
    }

    public void trigger(Event e) {
        e.setSource(this);
        e.setTime(System.currentTimeMillis());

        try {
            e.getCallback().invoke(e.getTarget(), e);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    public void trigger(Enum call) {
        if (!this.events.containsKey(call)) {
            return;
        }
        trigger(this.events.get(call).setTrigger(call.toString()));
    }

}
